import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an8 from '@mmstudio/an000008';
import an48 from '@mmstudio/an000048';
import { tbfdrole } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/role/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = Omit<ITbfdrole, 'roleid'>;

/**
 * 新增角色
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;

		if (!body
			|| !body.name
		) {
			res.status(200).json({
				ok: false,
				message: '角色名称不能为空'
			});
			return;
		}
		const r = await tbfdrole().first('*').where({
			name: body.name,
		});
		if (r) {
			res.status(200).json({ ok: false, message: '该角色已存在' });
			return;
		}
		const id = an8();
		await tbfdrole().insert({
			...body,
			roleid: id
		});
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
